﻿using Microsoft.Xna.Framework;
using System;
using Terraria;
using Terraria.GameInput;
using Terraria.ModLoader;

namespace HardcoreGame.Common.Players
{
    public static class MouseSyncPlayerExtensions
    {
        public static void SyncRightClick(this Player player) => player.GetModPlayer<MouseSyncingPlayer>().rightClickListener = true;
        public static void SyncMousePosition(this Player player) => player.GetModPlayer<MouseSyncingPlayer>().mouseWorldListener = true;
        public static void SyncMouseRotation(this Player player) => player.GetModPlayer<MouseSyncingPlayer>().mouseRotationListener = true;

        public static bool RightClicking(this Player player) => player.GetModPlayer<MouseSyncingPlayer>().mouseRight;
        public static Vector2 MouseWorld(this Player player) => player.GetModPlayer<MouseSyncingPlayer>().mouseWorld;
    }
    public class MouseSyncingPlayer : ModPlayer
    {
        public bool mouseRight = false;
        private bool oldMouseRight = false;
        public Vector2 mouseWorld;
        private Vector2 oldMouseWorld;
        public bool rightClickListener = false;
        public bool mouseWorldListener = false;
        public bool mouseRotationListener = false;
        public bool sendControls = false;

        public override void PreUpdate()
        {
            if (Main.myPlayer == Player.whoAmI)
            {
                mouseRight = PlayerInput.Triggers.Current.MouseRight;
                mouseWorld = Main.MouseWorld;
                if (rightClickListener && mouseRight != oldMouseRight)
                {
                    oldMouseRight = mouseRight;
                    sendControls = true;
                    rightClickListener = false;
                }
                if (mouseWorldListener && Vector2.Distance(mouseWorld, oldMouseWorld) > 10f)
                {
                    oldMouseWorld = mouseWorld;
                    sendControls = true;
                    mouseWorldListener = false;
                }
                if (mouseRotationListener && Math.Abs((mouseWorld - Player.MountedCenter).ToRotation() - (oldMouseWorld - Player.MountedCenter).ToRotation()) > 0.15f)
                {
                    oldMouseWorld = mouseWorld;
                    sendControls = true;
                    mouseRotationListener = false;
                }
                if (sendControls)
                {
                    sendControls = false;
                }
            }
        }
    }
}
